<template>
  <a-space v-if="!props.isInfo">
    <a-select style="width: 180px" placeholder="请选择属性" @change="changeAtt" allow-search v-model="selAttrId">
      <a-option v-for="(item, index) of attrDataList" :key="index" :value="item.id">{{ item.name }}</a-option>
    </a-select>
    <!-- <a-button class="gray-outline">新增</a-button> -->
    <a-popover>
      <icon-refresh class="cursor" style="font-size: 16px" @click="getList" />
      <template #content>
        <p>因为创建属性是异步操作，当发现下拉菜单里面没有新增的选项时，请点击此处刷新</p>
      </template>
    </a-popover>

    <a-button type="text" @click="showPropertyDetailModal = true">创建属性</a-button>
  </a-space>
  <a-table size="mini" :data="editSelAttr" :pagination="false" :loading="attrLoading" class="table-single-line mt5" :scroll="{ x: '100%', y: 300 }">
    <template #columns>
      <a-table-column title="属性ID" #cell="{ record }" :width="80">
        {{ record.id }}
      </a-table-column>
      <a-table-column title="属性名称" #cell="{ record }" :width="100">
        <a-space>
          <div>{{ record.name }}</div>
          <a-button type="text" @click="shoeEditPropertyModal(record)">编辑属性</a-button>
        </a-space>
      </a-table-column>
      <a-table-column title="可见性" #cell="{ record }" :width="100">
        <div v-if="!props.isInfo">
          <a-checkbox v-model="record.visible" disabled>产品页可见</a-checkbox>
          <a-checkbox v-model="record.variation">变体可用</a-checkbox>
        </div>
        <div v-else>
          <div v-if="record.visible">产品页可见</div>
          <div v-if="record.variation">变体可用</div>
        </div>
      </a-table-column>
      <a-table-column title="属性值" #cell="{ record }" :width="300">
        <a-button v-if="!props.isInfo" type="text" @click="showEditAttrValueModal(record)">编辑属性值</a-button>
        <a-button v-if="!props.isInfo" class="fr" type="text" @click="show(record)">添加属性值</a-button>
        <selPropertyValueList :data="record" />
        <!-- <TextLimit position="top" :val="record.selKey.join('，')"></TextLimit> -->
      </a-table-column>
      <a-table-column title="操作" #cell="{ record, rowIndex }" :width="30" v-if="!props.isInfo">
        <a-button type="text" style="color: red" @click="editSelAttr.splice(rowIndex, 1)">删除</a-button>
      </a-table-column>
    </template>
  </a-table>

  <quickAddAtt v-if="quickAddAttModal" v-model="quickAddAttModal" :id="id" :shopId="props.shopId" @save="saveAddAtt" />

  <editAttrValue v-if="editAttrValueModal" v-model="editAttrValueModal" :shopId="props.shopId" :info="addInfo" @save="saveAddValue" />

  <propertyDetail v-if="showPropertyDetailModal" v-model="showPropertyDetailModal" :info="editPropertyInfo" :type="type" :shopId="props.shopId" />
</template>

<script lang="ts" setup>
  import { onMounted, ref, watch } from 'vue'
  import { attributeRollPage } from '@/api/product'
  import quickAddAtt from '../../onlineProduct/components/quickAddAtt.vue'
  import editAttrValue from '../../onlineProduct/components/editAttrValue.vue'
  import propertyDetail from '../../onlineProduct/components/propertyDetail.vue'
  import selPropertyValueList from './selPropertyValueList.vue'
  import { Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  let props = defineProps(['modelValue', 'shopId', 'type', 'list', 'isInfo'])
  let emits = defineEmits(['save'])
  let id = ref('')
  let quickAddAttModal = ref(false)
  let attrLoading = ref(false)
  let editAttrValueModal = ref(false)
  let showPropertyDetailModal = ref(false)
  let attrDataList: any = ref([])
  let selAttrId = ref('')
  let type = ref('add')
  let editPropertyInfo = ref({})
  let addInfo = ref({})
  let propertyList: any = ref([])
  let editInfo: any = ref({
    options: [],
  })
  let editSelAttr: any = ref([])
  const getList = async () => {
    try {
      attrLoading.value = true
      const res: any = await attributeRollPage({ shopIdList: [props.shopId], pageSize: 999999 })
      let arr = res.data?.list || []
      propertyList.value = arr
      // 接口返回的数据处理成传参格式
      // console.log(arr, props.selAttList)
      arr.forEach((e: any) => {
        let obj = {
          id: e.dataFromRestApi.id || '',
          name: e.dataFromRestApi.name || '',
          options: e.termList ? e.termList.map((e: any) => e.dataFromRestApi.name) : [],
          position: 0,
          variation: true,
          visible: true,
        }
        attrDataList.value.push(obj)
      })
    } catch (error) {}
    attrLoading.value = false
  }

  const showEditAttrValueModal = (data: any) => {
    addInfo.value = data
    editAttrValueModal.value = true
  }

  const show = (data: any) => {
    id.value = data.id
    type.value = 'add'
    quickAddAttModal.value = true
  }

  const saveAddAtt = (name: string) => {
    let item = editSelAttr.value.find((e: any) => e.id == id.value)
    item.options.push(name)
    item.selKey.push(name)
  }

  const changeAtt = (val: string) => {
    let item = attrDataList.value.find((e: any) => e.id == val)
    let index = editSelAttr.value.findIndex((e: any) => e.id == item.id)
    selAttrId.value = ''
    if (index != -1) return
    if (item) {
      // 只取前100条
      item.selKey = [...item.options].slice(0, 100)
      item.selAll = true
      editSelAttr.value.push(item)
    }
  }

  const submit = () => {
    let arr = _.cloneDeep(editSelAttr.value)
    arr.map((e: any) => {
      e.options = e.selKey && [...e.selKey]
      return e
    })
    emits('save', arr)
  }

  const showData = () => {
    props.list.forEach((e: any) => {
      let data = attrDataList.value.find((item: any) => item.id == e.id)
      if (data) {
        data.selKey = [...e.options]
        editSelAttr.value.push(data)
      }
    })
  }

  const shoeEditPropertyModal = (data: any) => {
    let item = propertyList.value.find((e: any) => e.dataFromRestApi.id == data.id)
    if (!item) return Message.error('当前属性已不存在，不能编辑')
    editPropertyInfo.value = item || {}
    type.value = 'edit'
    showPropertyDetailModal.value = true
  }

  const saveAddValue = (data: any) => {
    let index = editSelAttr.value.findIndex((e: any) => e.id == data.id)
    if (index > -1) editSelAttr.value[index] = data
  }

  watch(
    () => editSelAttr,
    () => submit(),
    {
      deep: true,
    }
  )

  onMounted(async () => {
    await getList()
    // 编辑的时候回显属性
    if (props.type && props.list[0]) {
      showData()
    }
  })
</script>

<style lang="less" scoped>
  .title {
    width: 70px;
    text-align: right;
  }
</style>
